import WxValidate from '../../../utils/WxValidate.js';
import http from '../../../utils/http.js';
import ocr from '../../../utils/ocr.js';

import {
  getDicts
} from '../../../utils/dict.js';

const {
  $Message
} = require('../../../component/iview/base/index');


//基本信息
const vehicleField = [{
    "text": "登记证编号",
    "field": "registerNo",
    "scan": true,
    rule: {
      "required": false,
      "maxlength": 12,
      "minlength": 12,
      "number": true,
    },
    message: {
      "required": "登记证书编号不能为空",
      "maxlength": "登记证书编号不能超过12个字符",
      // "enNum": "登记证书编号只能是英文和数字"
      "number": "登记证书编号只能是数字"
    }
  },
  {
    "text": "车架号",
    "field": "vin",
    rule: {
      "required": true,
      "maxlength": 32,
      "enNum": true,
    },
    message: {
      "required": "车架号不能为空",
      "maxlength": "车架号不能超过32个字符",
      "enNum": '车架号只能输入英文和数字'
    }
  }, {
    "text": "车牌号码",
    "field": "plateNo",
    rule: {
      "required": true,
      "plateNo": true
    },
    message: {
      "required": "车牌号码不能为空"
    }
  }, {
    "text": "发动机号",
    "field": "engineNo",
    rule: {
      "required": true,
      "maxlength": 64,
      "lineEnNum": true
    },
    message: {
      "required": "发动机号不能为空",
      "maxlength": "发动机号不能超过64个字符",
      "lineEnNum": "发动机号只能是英文和数字和横杠"
    }
  }, {
    "text": "行驶证注册日期",
    "field": "registerDate",
    date: true,
  }, {
    "text": "行驶证签发日期",
    "field": "issueDate",
    date: true,
  }, {
    "text": "颜色",
    "field": "color",
    rule: {
      "maxlength": 16,
    },
    message: {
      "maxlength": "颜色不能超过16个字符",
    }
  }, {
    "text": "使用性质",
    "field": "useProperty",
    "category": "VEHICLE_USE_PROPERTY",
    select: true
  }, {
    "text": "号牌种类",
    "field": "plateType",
    "category": "VEHICLE_PLATE_TYPE",
    select: true,
  }, {
    "text": "出厂日期",
    "field": "productionDate",
    date: true,
  }, {
    "text": "车型",
    "field": "vehicleName",
    search: true,
    rule: {
      "required": true,
    },
    message: {
      "required": "请选择车型",    
    }
  },
];


Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeheight: 0,
    commission: null, //本次交易的费用
    show: false, //是否弹窗
    currentStep: 0,
    formField: vehicleField,
    files: {},// 保存图片base64
    filesFlag: {},//保存图片是否新增。1为新增0为存在数据
    filesField: [{
        text: '行驶证',
        field: 'vehicleLicense',
        hidden: true,
      }, {
        text: '车正脸照片',
        field: 'frontImg',
        "required": false,

      }, {
        text: '左前45度照片',
        field: 'leftFrontImg',
        "required": false,
      },
      {
        text: '右前45度照片',
        field: 'rightFrontImg',
        "required": false,
      }, {
        text: '正后方照片',
        field: 'backImg',
        "required": false,

      }, {
        text: '左后照片',
        field: 'leftBackImg',
        "required": false,
      }, {
        text: '侧面照片',
        field: 'sideImg',
        "required": false,
      },
      {
        text: '前排内饰',
        field: 'frontRowImg',
        "required": false,
      },
      {
        text: '后排内饰',
        field: 'backRowImg',
        "required": false,
      },
      {
        text: '主驾驶位照片 ',
        field: 'masterDriverImg',
        "required": false,
      },
      {
        text: '其他图片',
        field: 'otherImg0 ',
        "required": false,
      }, {
        text: '其他图片1',
        field: 'otherImg1',
        "required": false,
      }, {
        text: '其他图片2',
        field: 'otherImg2',
        "required": false,
      }, {
        text: '其他图片3',
        field: 'otherImg3',
        "required": false,
      }, {
        text: '其他图片4',
        field: 'otherImg4',
        "required": false,
      }, {
        text: '其他图片5',
        field: 'otherImg5',
        "required": false,
      }, {
        text: '其他图片6',
        field: 'otherImg6',
      },
    ],
    formDict: {
      "vehicle.isImported": [{
        code: 0,
        name: '非进口车'
      }, {
        code: 1,
        name: '进口车'
      }],
    },
    
    formData: {
      "vehicle.isImported": 0,
      "destination": '福建省厦门市',
    },
    formSelectData: {
      "vehicle.isImported": 0,
    },

    ocrFile: [{
      step: 0,
      field: 'vehicleLicense',
      text: '请上传行驶证主页照片，将自动识别信息',
      bgClass: 'vehicle-license-image'
    }, ],

    confirmShow: false, //用来展示是否切换个人和企业
    confirmField: '', //确定要更改的字段
    confirmValue: '', //确定要更改后的值
    srcollWidth: 0,
    files: {},
    filesFlag: {},
    selectDicts: [
      "useProperty", "plateType", "VEHICLE_TYPE", "fuelType", "VEHICLE_EMISSION_STANDARD", "vehicleType", "airAdmission", "cylinderArrangement", "valveTrain", "valveTrain", "fuelGrade", "fuelingMethod", "cylinderHead", "cylinderMaterial", "motorAmount", "motorLayout", "batteryType", "transmissionType", "drivingMethod", "fourWheelDriveTyp", "centralDifferentialStructure", "frontSuspensionType", "rearSuspensionType", "boostType", "carBodystructure", "frontBrakeType", "rearBrakeType", "parkingBrakeType", "spareTire", "kneeAirbags", "backRowAirbags", "backRowCenterAirbags", "passivePedestrianProtection", "tirePressureMonitoring", "zeroTireKeepGoing", "seatBeltReminder", "childSeatInterfaceISOFIX", "abs", "ebd", "eba", "asr", "esp", "blindSpotMonitoring", "ldws", "lkas", "trafficSignRecognition", "activeBrake", "fatigueDrivingWarning", "parkingRadar", "assistanceImage", "rcta", "acc", "drivingMode", "automaticParking", "startStop", "autoHold", "hillStartAssistControL", "hillDescentControl", "airSuspension", "eleSuspension", "variableRatio", "centralDifferentialLock", "sunroofType", "sportLookKit", "rimMaterial", "electricSuctionDoor", "slidingDoorType", "electricTrunk", "inductionTrunk", "roofRack", "engineAntiThef", "centralLockt", "keyType", "keylessStart", "remoteboot", "batteryPreheating", "steeringWheelMaterial", "steeringWheelPositionAdjust", "multifunctionWteeringWheel", "drivingComputerScreen", "fullLCDMeter", "headUpDisplay", "drivingRecorder", "materialOfSeats", "seatMemory", "rearSeatReclineForm", "rearCupShelf", "centralLCDScreen", "gps", "roadRescueCall", "bluetoothPhone", "telematics", "otaUpgrade", "lowBeamLights", "hightBeamLights", "lightingFeatures", "ledDaytimeLights", "adaptiveLight", "automaticHeadlight", "steeringAssistLight", "headlightHeightAdjustable", "headlightCleaning", "delayedHeadlightShutdown", "interiorAmbientLight", "oneButtonLift", "windowAntiPinch", "inductionWiper", "airConditioning", "rearAirConditioner", "rearAirOutlet", "temperatureZoneControl", "pm25"
    ] ,// 单选字典
    inputVal: "", // 搜索内容
    typeList: [],// 渲染用的只有name的数组
    typeListAll: [],// 带id的数组
    pickerView: false,//控制车型选择picker-view
    pvIndex: 0,
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let dictFieldArray = ["useProperty", "plateType", "VEHICLE_TYPE", "fuelType",
      "VEHICLE_EMISSION_STANDARD", "vehicleType", "airAdmission",
      "cylinderArrangement", "valveTrain", "fuelGrade", "fuelingMethod", "cylinderHead", "cylinderMaterial", "motorAmount",
      "motorLayout", "batteryType", "transmissionType", "drivingMethod", "fourWheelDriveType",
      "centralDifferentialStructure", "frontSuspensionType", "rearSuspensionType",
      "boostType", "carBodystructure", "frontBrakeType", "rearBrakeType", "parkingBrakeType", "spareTire",
      "airBag", "sideAirbags", "headAirbags", "tirePressureMonitoring", "seatBeltReminder",
      "parkingRadar", "assistanceImage", "acc", "drivingMode", "variableSuspension",
      // 操控配置
      "sunroofType", "rimMaterial", "slidingDoorType", "keyType",
      //内部配置
      "steeringWheelMaterial", "steeringWheelPositionAdjust", "drivingComputerScreen",
      // 座椅配置
      "materialOfSeats", "mainSeatAdjustmentMode", "secondSeatAdjustmentMode", "electricAdjustmentSeat", "frontSeatFunction", "seatMemory", "secondRowSeatAdjustment", "rearSeatFunction", "rearSeatReclineForm", "centerArmrest", "centralLCDScreen", "phoneConnection", "externalAudioInterface",
      // 灯光配置
      "lowBeamLights", "hightBeamLights", "lightingFeatures",
      // 玻璃后视镜
      "powerWindows", "oneButtonLift", "exteriorMirrorFunction", "makeUpMirro",
      // 感应雨刷
      "airConditioning",
    ];
    
    let formDict = this.data.formDict;
    let formData = this.data.formData;

    // 初始配置字典
    let formSelectData = this.data.formSelectData;
    
    this.setData({
      formSelectData: formSelectData,
      formData: formData,
    })
    let that = this;
    //初始化字典，后台提供字典数据
    this.loadDict(function(res) {
      if (res && res !== null) {
        if (options.id != null) {
          wx.showLoading({
            title: '数据准备中...',
            mask: true
          })
          http.request({
            url: '/vehicleInfo/detailForUpdate',
            method: 'get',
            data: {
              id: options.id
            },
            success(res){
              wx.hideLoading();
              let filesFlag = {};
              let filesField = that.data.filesField;
              let image = {};              
              let array = that.data.filesField;

              for (let i = 0; i < array.length; i++) {
                let field = array[i].field;
                if (res.image[filesField[i].field] != null && res.image[filesField[i].field] != '') {
                  // let src = http.apiUrl + http.imgUrl + "?imagePath=" + res.image[filesField[i].field] +
                  //   "&" + wx.getStorageSync("sessionid")
                  let src = 'data:image/jpeg;base64,' + res.image[filesField[i].field]
                  image[field] = encodeURI(src);
                  filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
                }
              }

              let formSelectData = that.data.formSelectData;
              for (let i = 0; i < dictFieldArray.length; i++) {
                that.dictToIndex(dictFieldArray[i], res[dictFieldArray[i]], formSelectData);
              }

              that.setData({
                formData: res,
                formSelectData: formSelectData,
                files: image,
                filesFlag: filesFlag,
                inputVal: res['vehicleName']
              });
            }
          });
        }
      }
    });
    this.initValidate();
    // 查看详情修改数据
  },
  //加载字典信息
  loadDict: function(callback) {
    var that = this;
    wx.showLoading({
      title: '数据准备中...',
      mask: true
    })

    let formField = this.data.formField;
    let categoryArray = [];
    let dictFieldArray = [];
    for (let i = 0; i < formField.length; i++) {
      const rule = {};
      const message = {};
      const multiple = {};        
      if (formField[i]["select"] === true && formField[i]["local"] !== true) {
        categoryArray.push(formField[i]["category"]);
        dictFieldArray.push(formField[i]["field"])
      }
      
    }
    getDicts(categoryArray, function(result) {

      for (let i = 0; i < categoryArray.length; i++) {
        that.handleDict(result[categoryArray[i]], dictFieldArray[i]);
      }

      wx.hideLoading()
      callback(result)
    })
  },



  // 初始化处理字典
  handleDict: function(dictList, field) {
    let formDict = this.data.formDict;
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    
    formDict[field] = dictList;
    formData[field] = dictList[0].code;
    formSelectData[field] = 0;
    this.setData({
      formDict: formDict,
      formData: formData,
      formSelectData: formSelectData
    });

  },
  // 获取车型输入框输入的文字
  getInputVal(e){
    let that = this,
        val = e.detail.value,
        field = e.currentTarget.dataset.field
    that.data.formData[field] = ''
    that.setData({
      inputVal: val,
      formData: that.data.formData
    });
  },
  // 搜索车型
  searchNow (e) {
    let that = this
    
    http.request({
      url: '/wxVehicleModel/nameAndId',
      method: 'get',
      data: {
        name: that.data.inputVal
      },
      success(res) {
        let list = []
        if (res.length != 0) {
          res.forEach(item => {
            list.push(item.vehicleName)
          })
          
          that.setData({
            typeList: list,
            typeListAll: res,
            pickerView: true,
          })
        }else{  
          $Message({
            content: '未找到该车型相关信息，请先进行车型录入',
            type: 'error'
          });          
        }
      }
    })
    

  },
  // 获取车型
  changeCarType(e){
    let val = e.detail.value[0],
          that = this        
    that.data.inputVal =  that.data.formData['vehicleName'] = that.data.typeList[val]   
    that.data.pvIndex = val
  },
  // 点击选择车型弹窗的确定按钮
  sureCarType(e){
    let that = this,
        pvIndex = that.data.pvIndex,
        formData = that.data.formData,
        typeListAll = that.data.typeListAll

    that.data.inputVal =  that.data.formData['vehicleName'] = typeListAll[pvIndex].vehicleName
    formData['detailId'] = typeListAll[pvIndex].id

    that.setData({
      pvIndex: that.data.pvIndex,
      formData: that.data.formData,
      inputVal: that.data.inputVal,
      pickerView: false
    })  
  },
  // 取消选择车型
  cancelBtn(e) {
    let that = this
    that.data.formData['vehicleName'] = ""    
    this.setData({
      pickerView: false,
      formData: that.data.formData
    })
  },
  
  //上传图片
  chooseImage: function(e) {
    let that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      //sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      count: 1,
      success: function(res) {
        let files = that.data.files;
        files[e.currentTarget.dataset.field] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[e.currentTarget.dataset.field] = 1; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag,
        });
      }
    })
  },
  // 图片预览
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.img, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.img] // 需要预览的图片http链接列表
    })
  },
  // 删除多图
  deleteImageList: function(e) {
    let that = this;
    var files = that.data.files;
    let msg = e.currentTarget.dataset.text;
    wx.showModal({
      title: '确认删除?',
      content: '请确认是否删除【' + msg + '】照片',
      success(res) {
        if (res.confirm) {
          files[e.currentTarget.dataset.field] = null;
          let filesFlag = that.data.filesFlag;
          filesFlag[e.currentTarget.dataset.field] = 1;
          that.setData({
            files: files,
            filesFlag: filesFlag
          });
     

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })  
  },
  imageToBase64: function(index, images) {
    let field = this.data.filesField[index]["field"];
    let files = this.data.files;
    let filesFlag = this.data.filesFlag;
    let formData = this.data.formData

    index++;
    // return;
    if (this.data.filesFlag[field] == 1) {
      //说明这张图片是新增
      if (this.data.files[field] === null) {
        images[field] = '';
        if (index < this.data.filesField.length) {
          this.imageToBase64(index, images);
        } else {
          this.saveData(images);
        }
      } else {
        let file = this.data.files[field];
        // return
        wx.getFileSystemManager().readFile({
          filePath: file, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            wx.hideLoading();
            images[field] = "data:image/jpeg;base64," + res.data;
          },
          complete: () => {
            if (index < this.data.filesField.length) {
              this.imageToBase64(index, images);
            } else {
              this.saveData(images);
            }
          }
        })
      }

    } else if (this.data.filesFlag[field] == 0) {
      //说明这张图片是修改时回显的
      images[field] = this.data.formData.image[field] //直接上传原先的地址
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    } else {
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    }
  },
  saveData: function(images) {
    var that = this;
    let formData = that.data.formData;
    
    let files = this.data.files,
        filesFlag = this.data.filesFlag
    // 车辆图片
    if (images != null) {

      for (let key in filesFlag) {
        if (filesFlag[key] == 0) {
          formData['image.'+key] = formData.imageUrl[key];
        }else{
          formData['image.'+key] = images[key];
        }
      }
    }
    for (let key in formData) {
      if (formData[key] == null || formData[key] == "") {
        delete formData[key];
      }
    }
    delete formData['image'];
    delete formData['imageUrl'];
    let data = JSON.parse(JSON.stringify(formData));

    // return
    http.request({
      url: '/vehicleInfo/save',
      data: data,
      success: (res) => {
        let pages = getCurrentPages();
        let prepage = pages[pages.length - 2];
        wx.hideLoading({});
        wx.navigateBack({
          delta: 1,
          complete: function() {
            //保存成功后，页面重新加载数据
            prepage.reloadData();
          }
        });
      },
      error: (res) => {
        wx.hideLoading({});
        $Message({
          content: "提交失败," + res.replace('ServiceException:', ''),
          type: 'error'
        });
      }
    });
  },


  // 下一步、顶部滑块
  slideTab: function() {
    let srcollWidth = this.data.srcollWidth;
    let currentStep = this.data.currentStep;
    let screenWidth = wx.getSystemInfoSync().windowWidth;    
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  dictToIndex: function(field, value, formSelectData) {
    if (value == null || value == "") {
      formSelectData[field] = 0;
      return formSelectData;
    }
    var dict = this.data.formDict[field];
    if (dict != null && dict.length > 0) {
      for (var i = 0; i < dict.length; i++) {
        if (dict[i].code == value) {          
          formSelectData[field] = i;
          break;
        }
      }
    }
    return formSelectData;
  },

  // 日期选择
  bindDateChange: function(e) {
    let formData = this.data.formData;
    formData[e.currentTarget.dataset.field] = e.detail.value;
    this.setData({
      formData: formData
    });
  },

  // 单选切换
  bindDictChange(e) {
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    let field = e.currentTarget.dataset.field;
    let index = e.detail.value;
    formSelectData[field] = index;
    formData[field] = this.data.formDict[field][index]["code"];
    if (field === "transferType" && formData[field] == 2) {
      let dict = this.data.formDict["tradeVehicleType"];
      let index = formSelectData["tradeVehicleType"];
      for (let i = 0; i < dict.length; i++) {
        if (dict[i]["code"] == "TRADE_TURN_OUT") {
          index = i;
        }
      }
      formSelectData["tradeVehicleType"] = index;
      formData["tradeVehicleType"] = "TRADE_TURN_OUT";
    }
    this.setData({
      formData: formData,
      formSelectData: formSelectData
    });
  },
  bindVal: function(e) {
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    let field = e.currentTarget.dataset.field;
    let value = e.detail.value;
    if (field === "vin") {
      if (value != null && value.length > 0) {
        if (value.substr(0, 1) == 'L') {
          formData["vehicle.isImported"] = 0;
          formSelectData["vehicle.isImported"] = 0;
        } else {
          formData["vehicle.isImported"] = 1;
          formSelectData["vehicle.isImported"] = 1;
        }
      }
    }
    formData[field] = value;
    this.setData({
      formData: formData,
      formSelectData: formSelectData
    });
  },

  //验证函数
  initValidate() {
    let formField = this.data.formField;
    let validate = [];      
    const rule = {};
    const message = {};      
    for (let i = 0; i < formField.length; i++) {
      rule[formField[i]["field"]] = formField[i]["rule"];
      message[formField[i]["field"]] = formField[i]["message"];
    }
    let wxValidate = new WxValidate(rule, message);
    validate.push(wxValidate);
    
    this.WxValidate = validate;
  },
  //调用验证函数
  formSubmit: function(e) {
    const params = e.detail.value;
    //校验表单
    if (!this.WxValidate[this.data.currentStep].checkForm(params)) {
      const error = this.WxValidate[this.data.currentStep].errorList[0];
      $Message({
        content: error.msg,
        type: 'error'
      });
      return false
    }
    this.setData({
      currentStep: this.data.currentStep + 1
    });
  },
  //提交保存数据
  sumbitData: function() {
    let file = this.data.files;
    this.setData({
      show: true
    })
  },


  //弹窗确认
  handleOK: function() {
    this.setData({
      show: false,
    })
    
    this.imageToBase64(0, {})
  },
  //弹窗取消
  handleCancel: function() {
    this.setData({
      show: false
    })
  },


  //上一步
  previous: function(e) {
    let srcollWidth = this.data.srcollWidth;
    let currentStep = this.data.currentStep;
    let screenWidth = wx.getSystemInfoSync().windowWidth;
    
    this.setData({
      currentStep: this.data.currentStep - 1
    });
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //
  handleCancel: function(e) {
    this.setData({
      show: false
    })
  },

  chooseWxImage: function(e) {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#000",
      success: function(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.doOcr(e, 'album')
          } else if (res.tapIndex == 1) {
            that.doOcr(e, 'camera')
          }
        }
      }
    })

  },

  //ocr图片识别
  doOcr: function(e, type) {
    var that = this;
    var imageType = 'VL';
    let currentStep = this.data.currentStep;
    // if (currentStep == 0) {
    //   imageType = 'VL';
    // } else if (currentStep == 2) {
    //   imageType = this.data.formData["buyer.creditType"];
    // } else if (currentStep == 3) {
    //   imageType = this.data.formData["seller.creditType"];
    // }
    wx.chooseImage({
      sizeType: ['compressed'],
      count: 1,
      sourceType: [type],
      success: function(res) {
        ocr.baiduOcr({
          imageType: imageType,
          filePath: res.tempFilePaths[0],
          success: function(resp) {
            // wx.showLoading({});
            // return;
            var formData = that.data.formData;
            var formSelectData = that.data.formSelectData;
            if (that.data.currentStep == 0) {
              formData["vin"] = resp["车辆识别代号"]["words"];
              formData["brandModel"] = resp["品牌型号"]["words"];
              formData["plateNo"] = resp["号牌号码"]["words"];
              formData["engineNo"] = resp["发动机号码"]["words"];
              if (formData["vin"].substr(0, 1) == 'L') {
                formData["vehicle.isImported"] = 0;
                formSelectData["vehicle.isImported"] = 0;
              } else {
                formData["vehicle.isImported"] = 1;
                formSelectData["vehicle.isImported"] = 1;
              }
              var carUsePropertyDict = that.data.formDict["useProperty"];
              if (carUsePropertyDict != null && carUsePropertyDict.length > 0) {
                var userProperty = resp["使用性质"]["words"];
                for (var i = 0; i < carUsePropertyDict.length; i++) {
                  if (carUsePropertyDict[i].name == userProperty) {
                    formData["useProperty"] = carUsePropertyDict[i].code;
                    formSelectData["useProperty"] = i;
                    break;
                  }
                }
              }
            }
            that.setData({
              formData: formData,
              formSelectData: formSelectData
            });
          },
        });

        let fileField = that.data.currentStep == 0 ? "vehicleLicense" :
          that.data.currentStep == 2 ? "buyerCreditFront" : "sellerCreditFront";
        let files = that.data.files;
        files[fileField] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[fileField] = 1; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag
        });
      }
    });
  },



  //二维码识别扫描
  getQRCode: function(e) {
    var _this = this;
    let formData = this.data.formData;
    wx.scanCode({ //扫描API
      success: function(res) {
        formData[e.currentTarget.dataset.field] = res.result;
        _this.setData({
          formData: formData,
        });
      }
    })
  },
  //chooseCity
  chooseCity: function(e) {
    let filed = e.currentTarget.dataset.field;
    let formData = this.data.formData;

    wx.navigateTo({
      url: '/pages/itemChose/index?filed=' + filed,
    })
  },
})